from fastapi import APIRouter, Request, HTTPException
from typing import Optional
from pathlib import Path

from service.youtube_downloader_service import YouTubeDownloaderService
from youtube_1080p_downloader_professional import YouTube1080pDownloader
from mrouter.domain.WxCloudRunHeader import WxCloudRunHeader
from utils.response import create_response
from config.logging_config import ProjectLoggers
from dto.youtube_request import (
    YouTubeInfoRequest, YouTubeDownloadRequest, YouTubeUrlRequest,
    YouTubeProfessionalDownloadRequest, YouTubeProfessionalValidateRequest
)
from dto.youtube_response import (
    YouTubeInfoResponse, YouTubeDownloadResponse, YouTubeDownloadUrlResponse,
    YouTubeSupportedQualitiesResponse
)

logger = ProjectLoggers.get_service_logger()
router = APIRouter(prefix="/youtube", tags=["YouTube视频下载"])

# 创建服务实例
youtube_service = YouTubeDownloaderService()
# 创建专业下载器实例
professional_downloader = YouTube1080pDownloader("./downloads/professional")

@router.post("/info", response_model=YouTubeInfoResponse)
async def get_youtube_video_info(
    request: Request,
    info_request: YouTubeInfoRequest
):
    """
    获取YouTube视频信息
    
    - **youtube_url**: YouTube视频链接
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取YouTube视频信息: {info_request.youtube_url}")
        
        # 调用服务获取视频信息
        result = await youtube_service.get_video_info(info_request.youtube_url)
        
        if result["success"]:
            logger.info(f"成功获取YouTube视频信息: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取视频信息",
                data=result["data"]
            )
        else:
            logger.warning(f"获取YouTube视频信息失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"YouTube视频信息请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取YouTube视频信息接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/download-url-advanced", response_model=YouTubeDownloadUrlResponse)
async def get_youtube_download_url_advanced(
    request: Request,
    url_request: YouTubeUrlRequest
):
    """
    获取YouTube视频下载链接 - 高级模式（多策略绕过限制）
    
    使用多种策略尝试获取高清视频：
    1. iOS客户端模拟
    2. Android客户端模拟  
    3. Web客户端高级配置
    4. 降级策略
    
    - **youtube_url**: YouTube视频链接
    - **quality**: 视频质量（360p, 480p, 720p, 1080p, best, worst）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求高级YouTube下载链接: {url_request.youtube_url}, 质量: {url_request.quality}")
        
        # 调用高级服务获取下载链接
        result = await youtube_service.get_download_urls_advanced(
            youtube_url=url_request.youtube_url,
            quality=url_request.quality
        )
        
        if result["success"]:
            data = result["data"]
            strategy_used = data.get("strategy_used", "未知策略")
            
            logger.info(f"高级策略成功获取YouTube下载链接: {data['title']} - 使用策略: {strategy_used}")
            
            return create_response(
                code=200,
                msg=f"成功获取下载链接 (策略: {strategy_used})",
                data=data
            )
        else:
            logger.warning(f"高级策略获取YouTube下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"高级YouTube下载链接请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"高级YouTube下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/download-url", response_model=YouTubeDownloadUrlResponse)
async def get_youtube_download_url(
    request: Request,
    url_request: YouTubeUrlRequest
):
    """
    获取YouTube视频直接下载链接
    
    - **youtube_url**: YouTube视频链接
    - **quality**: 视频质量（360p, 480p, 720p, 1080p, best, worst）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求获取YouTube下载链接: {url_request.youtube_url}, 质量: {url_request.quality}")
        
        # 调用服务获取下载链接（智能音频处理）
        result = await youtube_service.get_download_urls_with_audio_fallback(
            youtube_url=url_request.youtube_url,
            quality=url_request.quality
        )
        
        if result["success"]:
            logger.info(f"成功获取YouTube下载链接: {result['data']['title']}")
            return create_response(
                code=200,
                msg="成功获取下载链接",
                data=result["data"]
            )
        else:
            logger.warning(f"获取YouTube下载链接失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"YouTube下载链接请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"获取YouTube下载链接接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/download", response_model=YouTubeDownloadResponse)
async def download_youtube_video(
    request: Request,
    download_request: YouTubeDownloadRequest
):
    """
    下载YouTube视频到七牛云
    
    - **youtube_url**: YouTube视频链接
    - **quality**: 视频质量（360p, 480p, 720p, 1080p, best, worst）
    - **upload_to_qiniu**: 是否上传到七牛云存储
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求下载YouTube视频: {download_request.youtube_url}, 质量: {download_request.quality}")
        
        # 调用服务下载视频
        result = await youtube_service.download_video(
            youtube_url=download_request.youtube_url,
            quality=download_request.quality,
            upload_to_qiniu=download_request.upload_to_qiniu
        )
        
        if result["success"]:
            logger.info(f"成功下载YouTube视频: {result['data']['title']}")
            return create_response(
                code=200,
                msg="视频下载成功",
                data=result["data"]
            )
        else:
            logger.warning(f"下载YouTube视频失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"YouTube视频下载请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"下载YouTube视频接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/qualities", response_model=YouTubeSupportedQualitiesResponse)
async def get_supported_qualities():
    """
    获取支持的视频质量选项
    """
    try:
        qualities = ["360p", "480p", "720p", "1080p", "best", "worst"]
        
        result = {
            "qualities": qualities,
            "default_quality": "720p",
            "description": "360p-1080p为固定分辨率，best为最佳质量，worst为最低质量"
        }
        
        return create_response(
            code=200,
            msg="获取支持的质量选项成功",
            data=result
        )
        
    except Exception as e:
        logger.error(f"获取支持质量选项接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/quick-download")
async def quick_download_youtube_video(
    request: Request,
    youtube_url: str,
    quality: Optional[str] = "720p"
):
    """
    快速下载YouTube视频（简化接口）
    
    - **youtube_url**: YouTube视频链接
    - **quality**: 视频质量，默认720p
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求快速下载YouTube视频: {youtube_url}")
        
        # 验证YouTube URL
        if not youtube_url:
            return create_response(code=400, msg="YouTube链接不能为空")
        
        # 简单验证YouTube链接
        valid_domains = ['youtube.com', 'www.youtube.com', 'm.youtube.com', 'youtu.be']
        if not any(domain in youtube_url for domain in valid_domains):
            return create_response(code=400, msg="请提供有效的YouTube链接")
        
        # 调用服务下载视频
        result = await youtube_service.download_video(
            youtube_url=youtube_url,
            quality=quality or "720p",
            upload_to_qiniu=True
        )
        
        if result["success"]:
            data = result["data"]
            response_data = {
                "title": data["title"],
                "download_url": data.get("qiniu_url", data.get("local_path")),
                "file_size": data["file_size_display"],
                "format": data["format"],
                "duration": data.get("duration")
            }
            
            logger.info(f"快速下载YouTube视频成功: {data['title']}")
            return create_response(
                code=200,
                msg="视频下载成功",
                data=response_data
            )
        else:
            logger.warning(f"快速下载YouTube视频失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except Exception as e:
        logger.error(f"快速下载YouTube视频接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/hls-info", response_model=YouTubeDownloadUrlResponse)
async def get_youtube_hls_streams_info(
    request: Request,
    url_request: YouTubeUrlRequest
):
    """
    通过HLS流解析获取YouTube视频信息 - 最新高级方法
    
    这是一个更底层的方法，通过解析YouTube播放器配置直接获取HLS流信息：
    1. 解析视频页面播放器配置
    2. 提取分离的音视频流URL
    3. 选择最佳H.264编码的高清流
    4. 为FFmpeg合成做准备
    
    - **youtube_url**: YouTube视频链接
    - **quality**: 视频质量（360p, 480p, 720p, 1080p）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求HLS流解析YouTube视频: {url_request.youtube_url}, 质量: {url_request.quality}")
        
        # 调用HLS流解析服务
        result = await youtube_service.get_hls_streams_and_merge(
            youtube_url=url_request.youtube_url,
            quality=url_request.quality
        )
        
        if result["success"]:
            data = result["data"]
            logger.info(f"HLS流解析成功: {data['title']} - 分辨率: {data['resolution']}")
            
            return create_response(
                code=200,
                msg="HLS流解析成功",
                data=data
            )
        else:
            logger.warning(f"HLS流解析失败: {result['error']}")
            return create_response(code=400, msg=result["error"])
            
    except ValueError as e:
        logger.warning(f"HLS流解析请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"HLS流解析接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/hls-download", response_model=YouTubeDownloadResponse)
async def download_youtube_hls_and_merge(
    request: Request,
    download_request: YouTubeDownloadRequest
):
    """
    通过HLS流下载并FFmpeg合成YouTube高清视频 - 终极方法
    
    这是最高级的下载方法，完整流程：
    1. 解析YouTube播放器获取分离的音视频流
    2. 下载高清H.264视频流
    3. 下载AAC音频流
    4. 使用FFmpeg合成完整的MP4文件
    5. 可选择上传到七牛云存储
    
    - **youtube_url**: YouTube视频链接
    - **quality**: 视频质量（360p, 480p, 720p, 1080p）
    - **upload_to_qiniu**: 是否上传到七牛云存储
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求HLS下载YouTube视频: {download_request.youtube_url}, 质量: {download_request.quality}")
        
        import tempfile
        import os
        
        # 创建临时输出文件
        temp_dir = tempfile.mkdtemp(prefix="youtube_hls_download_")
        output_filename = f"youtube_hls_{download_request.quality}.mp4"
        output_path = os.path.join(temp_dir, output_filename)
        
        try:
            # 调用HLS下载和合成服务
            result = await youtube_service.download_hls_and_merge(
                youtube_url=download_request.youtube_url,
                output_path=output_path,
                quality=download_request.quality
            )
            
            if not result["success"]:
                return create_response(code=400, msg=result["error"])
            
            stream_info = result["stream_info"]
            file_size_mb = result["file_size_mb"]
            
            # 构造响应数据
            response_data = {
                "video_id": stream_info["video_id"],
                "title": stream_info["title"],
                "format": stream_info["format"],
                "resolution": stream_info["resolution"],
                "duration": stream_info["duration"],
                "file_size_mb": file_size_mb,
                "thumbnail": stream_info["thumbnail"],
                "download_method": "HLS流下载 + FFmpeg合成",
                "is_hd": stream_info["is_hd"],
                "is_full_hd": stream_info["is_full_hd"],
                "has_audio": result["has_audio"],
                "vcodec": stream_info["vcodec"],
                "acodec": stream_info["acodec"],
                "fps": stream_info["fps"],
                "video_bitrate": stream_info["video_bitrate"],
                "audio_bitrate": stream_info["audio_bitrate"],
                "proxy_used": stream_info.get("proxy_used"),
                "local_file_path": output_path,
                "author": stream_info.get("author", "Unknown"),
                "view_count": stream_info.get("view_count", 0)
            }
            
            # 如果需要上传到七牛云
            if download_request.upload_to_qiniu:
                from service.qiniu_image_service import QiniuImageService
                qiniu_service = QiniuImageService()
                
                logger.info("🚀 开始上传到七牛云...")
                upload_result = await qiniu_service.upload_video_file(
                    file_path=output_path,
                    filename=f"{stream_info['video_id']}_{download_request.quality}.mp4"
                )
                
                if upload_result["success"]:
                    response_data.update({
                        "qiniu_uploaded": True,
                        "qiniu_url": upload_result["url"],
                        "qiniu_key": upload_result["key"]
                    })
                    logger.info(f"✅ 七牛云上传成功: {upload_result['url']}")
                else:
                    response_data.update({
                        "qiniu_uploaded": False,
                        "qiniu_error": upload_result["error"]
                    })
                    logger.warning(f"七牛云上传失败: {upload_result['error']}")
            else:
                response_data["qiniu_uploaded"] = False
            
            logger.info(f"✅ HLS下载和合成完成: {stream_info['title']} ({file_size_mb}MB)")
            
            return create_response(
                code=200,
                msg="HLS视频下载和合成成功",
                data=response_data
            )
            
        finally:
            # 清理临时文件
            try:
                import shutil
                if os.path.exists(temp_dir):
                    shutil.rmtree(temp_dir)
            except Exception as e:
                logger.warning(f"临时文件清理失败: {str(e)}")
                
    except ValueError as e:
        logger.warning(f"HLS下载请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"HLS下载接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/professional-download")
async def professional_download_youtube_video(
    request: Request,
    download_request: YouTubeProfessionalDownloadRequest
):
    """
    YouTube 1080p 专业下载器 - 生产级稳定性
    
    特点：
    - 智能质量选择：1080p → 720p → 480p 自动降级
    - 网络重试机制：指数退避重试策略（最多3次）
    - 详细日志记录：完整的下载过程追踪
    - 错误处理：多层次错误处理机制
    - 用户代理轮换：避免检测和限制
    - 代理支持：支持HTTP/HTTPS/SOCKS5代理
    - Cookie认证：支持YouTube cookies绕过机器人检测
    
    - **youtube_url**: YouTube视频链接
    - **quality**: 目标视频质量（1080p, 720p, 480p, best）
    - **upload_to_qiniu**: 是否上传到七牛云存储
    - **proxy_url**: 代理服务器URL（如：http://127.0.0.1:7890，可选）
    - **cookies_file**: YouTube cookies文件路径（如：./youtube_cookies.txt，可选但推荐）
    """
    try:
        # 获取用户OpenID用于日志记录
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求专业下载器下载: {download_request.youtube_url}, 质量: {download_request.quality}")
        
        # 参数验证已在DTO中完成，直接使用
        
        import asyncio
        import os
        import tempfile
        import time
        from pathlib import Path
        
        start_time = time.time()
        
        # 设置代理配置
        if download_request.proxy_url:
            professional_downloader.set_proxy(download_request.proxy_url)
            logger.info(f"🌐 使用指定代理: {download_request.proxy_url}")
        
        # 设置cookies文件
        if download_request.cookies_file:
            professional_downloader.set_cookies_file(download_request.cookies_file)
            logger.info(f"🍪 使用指定cookies文件: {download_request.cookies_file}")
        
        # 在新线程中运行同步的下载方法
        def sync_download():
            """同步下载函数"""
            return professional_downloader.download(download_request.youtube_url, download_request.quality)
        
        # 异步执行下载
        logger.info(f"🚀 开始使用专业下载器下载: {download_request.quality} 质量")
        loop = asyncio.get_event_loop()
        download_success = await loop.run_in_executor(None, sync_download)
        
        if not download_success:
            logger.error("专业下载器下载失败")
            return create_response(code=400, msg="专业下载器下载失败，请检查URL或网络连接")
        
        download_time = time.time() - start_time
        logger.info(f"✅ 专业下载器下载完成，耗时: {download_time:.2f} 秒")
        
        # 查找下载的文件
        download_dir = Path("./downloads/professional")
        downloaded_files = list(download_dir.glob("*.mp4"))
        
        if not downloaded_files:
            # 也检查其他常见视频格式
            downloaded_files = list(download_dir.glob("*.webm")) + list(download_dir.glob("*.mkv"))
        
        if not downloaded_files:
            logger.error("未找到下载的文件")
            return create_response(code=500, msg="下载完成但未找到文件")
        
        # 获取最新下载的文件
        latest_file = max(downloaded_files, key=os.path.getctime)
        file_size = latest_file.stat().st_size
        file_size_mb = file_size / (1024 * 1024)
        
        logger.info(f"📁 找到下载文件: {latest_file.name} ({file_size_mb:.2f}MB)")
        
        # 从专业下载器获取视频信息
        try:
            video_info = professional_downloader.extract_video_info(download_request.youtube_url)
            if video_info:
                title = video_info.get('title', latest_file.stem)
                duration = video_info.get('duration', 0)
                uploader = video_info.get('uploader', 'Unknown')
                thumbnail = video_info.get('thumbnail', '')
                video_id = video_info.get('id', '')
                view_count = video_info.get('view_count', 0)
                description = video_info.get('description', '')
            else:
                raise Exception("无法获取视频信息")
        except Exception as e:
            logger.warning(f"获取视频信息失败，使用默认值: {e}")
            title = latest_file.stem
            duration = 0
            uploader = 'Unknown'
            thumbnail = ''
            video_id = ''
            view_count = 0
            description = ''
        
        # 构造响应数据
        response_data = {
            "success": True,
            "download_method": "YouTube 1080p 专业下载器",
            "title": title,
            "uploader": uploader,
            "video_id": video_id,
            "duration": duration,
            "duration_string": f"{duration//60}:{duration%60:02d}" if duration > 0 else "Unknown",
            "view_count": view_count,
            "description": description[:200] + "..." if len(description) > 200 else description,
            "thumbnail": thumbnail,
            "local_file_path": str(latest_file),
            "filename": latest_file.name,
            "file_size": file_size,
            "file_size_mb": round(file_size_mb, 2),
            "file_size_display": f"{file_size_mb:.2f}MB",
            "format": latest_file.suffix[1:].upper(),
            "download_time_seconds": round(download_time, 2),
            "quality_requested": download_request.quality,
            "proxy_used": download_request.proxy_url or professional_downloader.proxy_config,
            "cookies_used": download_request.cookies_file or professional_downloader.cookies_file,
            "features": [
                "智能质量降级",
                "网络重试机制", 
                "用户代理轮换",
                "详细日志记录",
                "生产级稳定性",
                "代理支持" if (download_request.proxy_url or professional_downloader.proxy_config) else "直连模式",
                "Cookie认证" if (download_request.cookies_file or professional_downloader.cookies_file) else "无Cookie"
            ]
        }
        
        # 如果需要上传到七牛云
        if download_request.upload_to_qiniu:
            try:
                from service.qiniu_image_service import QiniuImageService
                qiniu_service = QiniuImageService()
                
                logger.info("🚀 开始上传到七牛云...")
                upload_start_time = time.time()
                
                # 生成唯一的文件名
                qiniu_filename = f"professional_{video_id or 'unknown'}_{download_request.quality}_{int(time.time())}.{latest_file.suffix[1:]}"
                
                upload_result = await qiniu_service.upload_video_file(
                    file_path=str(latest_file),
                    filename=qiniu_filename
                )
                
                upload_time = time.time() - upload_start_time
                
                if upload_result["success"]:
                    response_data.update({
                        "qiniu_uploaded": True,
                        "qiniu_url": upload_result["url"],
                        "qiniu_key": upload_result["key"],
                        "upload_time_seconds": round(upload_time, 2),
                        "cdn_url": upload_result["url"]  # 添加CDN URL
                    })
                    logger.info(f"✅ 七牛云上传成功: {upload_result['url']} (耗时: {upload_time:.2f}s)")
                else:
                    response_data.update({
                        "qiniu_uploaded": False,
                        "qiniu_error": upload_result["error"],
                        "upload_time_seconds": round(upload_time, 2)
                    })
                    logger.warning(f"❌ 七牛云上传失败: {upload_result['error']}")
                    
            except Exception as e:
                logger.error(f"七牛云上传异常: {str(e)}")
                response_data.update({
                    "qiniu_uploaded": False,
                    "qiniu_error": f"上传异常: {str(e)}"
                })
        else:
            response_data["qiniu_uploaded"] = False
            response_data["message"] = "未请求上传到七牛云"
        
        # 清理旧文件（可选，保留最近5个文件）
        try:
            all_files = sorted(download_dir.glob("*.*"), key=os.path.getctime, reverse=True)
            files_to_delete = all_files[5:]  # 保留最新的5个文件
            for old_file in files_to_delete:
                try:
                    old_file.unlink()
                    logger.info(f"🗑️ 清理旧文件: {old_file.name}")
                except Exception as e:
                    logger.warning(f"清理文件失败: {e}")
        except Exception as e:
            logger.warning(f"文件清理过程异常: {e}")
        
        total_time = time.time() - start_time
        logger.info(f"🎉 专业下载器任务完成: {title} (总耗时: {total_time:.2f}s)")
        
        return create_response(
            code=200,
            msg=f"专业下载器下载成功 - {title}",
            data=response_data
        )
        
    except ValueError as e:
        logger.warning(f"专业下载器请求参数验证失败: {str(e)}")
        return create_response(code=400, msg=str(e))
    except Exception as e:
        logger.error(f"专业下载器接口异常: {str(e)}")
        import traceback
        logger.error(f"异常堆栈: {traceback.format_exc()}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.get("/professional-status")
async def get_professional_downloader_status():
    """
    获取专业下载器状态信息
    """
    try:
        from youtube_1080p_downloader_professional import YouTubeDownloaderConfig
        import os
        
        download_dir = Path("./downloads/professional")
        download_dir.mkdir(parents=True, exist_ok=True)
        
        # 统计下载文件信息
        video_files = list(download_dir.glob("*.mp4")) + list(download_dir.glob("*.webm")) + list(download_dir.glob("*.mkv"))
        total_files = len(video_files)
        total_size = sum(f.stat().st_size for f in video_files)
        total_size_mb = total_size / (1024 * 1024)
        
        # 最近下载的文件
        recent_files = []
        if video_files:
            sorted_files = sorted(video_files, key=os.path.getctime, reverse=True)[:5]
            for file in sorted_files:
                file_stat = file.stat()
                recent_files.append({
                    "filename": file.name,
                    "size_mb": round(file_stat.st_size / (1024 * 1024), 2),
                    "created_time": file_stat.st_ctime,
                    "format": file.suffix[1:].upper()
                })
        
        status_data = {
            "downloader_version": "1.0.0",
            "status": "运行中",
            "download_directory": str(download_dir.absolute()),
            "total_downloaded_files": total_files,
            "total_storage_used_mb": round(total_size_mb, 2),
            "recent_downloads": recent_files,
            "configuration": {
                "max_retries": YouTubeDownloaderConfig.MAX_RETRIES,
                "retry_delay_base": YouTubeDownloaderConfig.RETRY_DELAY_BASE,
                "retry_delay_max": YouTubeDownloaderConfig.RETRY_DELAY_MAX,
                "download_timeout": YouTubeDownloaderConfig.DOWNLOAD_TIMEOUT,
                "supported_qualities": ["1080p", "720p", "480p", "best"],
                "quality_fallback_strategy": YouTubeDownloaderConfig.QUALITY_FALLBACK,
                "user_agents_count": len(YouTubeDownloaderConfig.USER_AGENTS)
            },
            "features": [
                "智能质量选择 (1080p → 720p → 480p)",
                "网络重试机制 (指数退避)",
                "用户代理轮换 (防检测)",
                "详细日志记录",
                "错误处理和恢复",
                "无需cookie文件",
                "生产级稳定性"
            ],
            "performance_tips": [
                "使用稳定的网络连接",
                "选择合适的视频质量",
                "避免频繁下载",
                "监控日志文件"
            ]
        }
        
        return create_response(
            code=200,
            msg="专业下载器状态获取成功",
            data=status_data
        )
        
    except Exception as e:
        logger.error(f"获取专业下载器状态异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}")

@router.post("/professional-validate")
async def validate_youtube_url_professional(
    request: Request,
    validate_request: YouTubeProfessionalValidateRequest
):
    """
    使用专业下载器验证YouTube URL
    
    - **youtube_url**: YouTube视频链接
    """
    try:
        user_openid = await WxCloudRunHeader.get_openid(request)
        logger.info(f"用户 {user_openid or 'anonymous'} 请求验证YouTube URL: {validate_request.youtube_url}")
        
        # 参数验证已在DTO中完成，直接使用
        
        # 使用专业下载器的URL验证器
        from youtube_1080p_downloader_professional import YouTubeURLValidator
        validator = YouTubeURLValidator()
        
        # 验证URL格式
        is_valid = validator.validate_youtube_url(validate_request.youtube_url)
        video_id = validator.extract_video_id(validate_request.youtube_url)
        
        if not is_valid:
            return create_response(
                code=400, 
                msg="无效的YouTube URL",
                data={"is_valid": False, "video_id": None}
            )
        
        if not video_id:
            return create_response(
                code=400, 
                msg="无法提取视频ID",
                data={"is_valid": False, "video_id": None}
            )
        
        # 尝试获取视频信息验证可访问性
        try:
            video_info = professional_downloader.extract_video_info(validate_request.youtube_url)
            if video_info:
                validation_data = {
                    "is_valid": True,
                    "video_id": video_id,
                    "title": video_info.get('title', 'Unknown'),
                    "duration": video_info.get('duration', 0),
                    "uploader": video_info.get('uploader', 'Unknown'),
                    "view_count": video_info.get('view_count', 0),
                    "is_live": video_info.get('is_live', False),
                    "thumbnail": video_info.get('thumbnail', ''),
                    "availability": "可下载"
                }
                
                logger.info(f"✅ URL验证成功: {video_info.get('title', 'Unknown')}")
                
                return create_response(
                    code=200,
                    msg="YouTube URL验证成功",
                    data=validation_data
                )
            else:
                return create_response(
                    code=400,
                    msg="视频信息获取失败，可能是私有视频或已删除",
                    data={"is_valid": False, "video_id": video_id, "availability": "不可访问"}
                )
                
        except Exception as e:
            logger.warning(f"视频信息获取异常: {str(e)}")
            return create_response(
                code=400,
                msg=f"视频验证失败: {str(e)}",
                data={"is_valid": False, "video_id": video_id, "error": str(e)}
            )
        
    except Exception as e:
        logger.error(f"URL验证接口异常: {str(e)}")
        return create_response(code=500, msg=f"服务器内部错误: {str(e)}") 